<template>
    <view class="container">
        <NavBar title="添加合同计量" @back="goBack" />
        <scroll-view class="form-content" scroll-y>
            <!-- 表单内容 -->
            <view class="form-list">
                <!-- 清单编号 -->
                <view class="form-item">
                    <text class="form-label">清单编号</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="text" v-model="form.costNumber" placeholder="请输入"
                            disabled="disabled" />
                    </view>
                </view>

                <!-- 清单名称 -->
                <view class="form-item">
                    <text class="form-label">清单名称</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="text" v-model="form.costName" placeholder="请输入"
                            disabled="disabled" />
                    </view>
                </view>

                <!-- 计量单号 -->
                <view class="form-item">
                    <text class="form-label">计量单号</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="text" v-model="form.meteringNumbers" placeholder="请输入"
                            disabled="disabled" />
                    </view>
                </view>
				<!-- 上限量 -->
				<!-- <view class="form-item">
				    <text class="form-label">上限量</text>
				    <view class="input-wrapper">
				        <input class="form-input" type="text" v-model="form.upperlimitNum" placeholder="请输入" />
				    </view>
				</view> -->
                <view class="form-item">
                    <text class="form-label">工程量</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="number" @blur="blur('projectNum')" v-model="form.projectNum" :placeholder="projectNum" />
                    </view>
                </view>
                <!-- <view class="form-item">
                    <text class="form-label">金额</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="text" v-model="form.meteringMoney" placeholder="请输入" />
                    </view>
                </view> -->
                <view class="form-item">
                    <text class="form-label">部位</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="text" v-model="form.jlPosition" placeholder="请输入" />
                    </view>
                </view>
				<view class="form-item">
				    <text class="form-label">分项(桩号)</text>
				    <view class="input-wrapper">
				        <input class="form-input" type="text" v-model="form.fxStationNumber" placeholder="请输入" />
				    </view>
				</view>
				<view class="form-item">
				    <text class="form-label">图号</text>
				    <view class="input-wrapper">
				        <input class="form-input" type="text" v-model="form.imgNum" placeholder="请输入" />
				    </view>
				</view>
				<view class="form-item">
				    <text class="form-label">交工证书</text>
				    <view class="input-wrapper">
				        <input class="form-input" type="text" v-model="form.handoverCertificate" placeholder="请输入" />
				    </view>
				</view>
				<view class="form-item textarea">
				    <text class="form-label">计算式</text>
				    <view class="input-wrapper ">
				        <uv-textarea v-model="form.calculationFormula" placeholder="请输入内容" height=80></uv-textarea>
				    </view>
				</view>

               

                <!-- 本期末量 -->
                <!-- <view class="form-item">
                    <text class="form-label">本期末量</text>
                    <view class="input-wrapper">
                        <input class="form-input" type="text" v-model="form.totalProjectNum" placeholder="请输入" />
                    </view>
                </view> -->

                <view class="submit-button">
                    <button class="submit-btn" @click="submitForm">提交</button>
                </view>
				<view class="blank_box">
					
				</view>
            </view>
        </scroll-view>
    </view>
</template>

<script>
import NavBar from '@/components/NavBar/index.vue'
import {
    addMeteringpay,
    getTotal
} from '@/utils/app.js'
export default {
    components: {
        NavBar
    },
    data() {
        return {
            id: '',
            supplierList: [{
                id: 1,
                name: '供应商1'
            },
            {
                id: 2,
                name: '供应商2'
            },
            {
                id: 3,
                name: '供应商3'
            }
            ],
            contractList: [{
                id: 1,
                name: '合同1'
            },
            {
                id: 2,
                name: '合同2'
            },
            {
                id: 3,
                name: '合同3'
            }
            ],
            categoryList: [{
                id: 1,
                name: '挖掘机'
            },
            {
                id: 2,
                name: '推土机'
            },
            {
                id: 3,
                name: '装载机'
            },
            {
                id: 4,
                name: '起重机'
            }
            ],
            form: {
                dataSource: 1,
                jlType: 1,
                nodeType: 1,
                supplier: '',
                contract: '',
                id: '',
                name: '',
                category: '',
                costNumber: '',
                costName: '',
                projectId: '',
                contractId: '',
                cycleId: '',
                sourceId: '',
                unitPrice: '',
                upperlimitNum: '',
                meteringNumbers: '',
                projectNum: '',
                // meteringMoney: '',
                jlPosition: '',
                totalProjectNum: '',
                addNum: '',
				level:'',
            },
            gettime: '',
			projectNum:'可计量数量xx'
        }
    },
    onLoad(options) {
        if (options.id) {
            this.id = options.id;
            // 可以根据ID加载设备信息填充表单
            this.form.id = this.id;
        }

        // 检查options.data是否存在
        if (options.data) {
			console.log(options.data);
            try {
                const parsedData = JSON.parse(decodeURIComponent(options.data));

                if (parsedData) {
                    this.form.costNumber = parsedData.number || '';
                    this.form.costName = parsedData.label || '';
                    this.form.projectId = parsedData.projectId || '';
                    this.form.contractId = parsedData.contractId || '';
                    this.form.cycleId = parsedData.cycleId || '';
                    this.form.sourceId = parsedData.sourceId || '';
                    this.form.unitPrice = parsedData.unitPrice || '';
                    this.form.upperlimitNum = parsedData.upperlimitNum || 0;
                    this.form.addNum = parsedData.addNum || '';
					this.form.level = parsedData.level || '';
                    this.getTotalData(parsedData);
					let upperlimitNum = parseFloat(this.form.upperlimitNum)
					let addNum = parseFloat(this.form.addNum)
					this.projectNum = `可计量数量${upperlimitNum - addNum }`
                }
            } catch (error) {
                uni.showToast({
                    title: '数据解析失败',
                    icon: 'none'
                });
            }
        } else {
            console.warn('未接收到数据参数');
        }
    },
    methods: {
		blur(e){
			if(this.form[e] < 0){
				this.form[e] = ''
				uni.showToast({
				    title: '只能输入大于0的数字',
				    icon: 'none'
				});
			}
		},
        onPullDownRefresh() {
            this.getTotalData(this.form)
        },
        getTotalData(parsedData) {
            let data = {
                projectId: parsedData.projectId,
                contractId: parsedData.contractId,
                cycleId: parsedData.cycleId
            }
            let yy = new Date().getFullYear();
            let mm = String(new Date().getMonth() + 1);
            let dd = String(new Date().getDate());
            if (Number(mm) < 10) {
                mm = '0' + mm;
            }
            if (Number(dd) < 10) {
                dd = '0' + dd;
            }
            getTotal(data).then(res => {
                this.gettime = yy + '' + mm + '' + dd + 'ht000' + res.data;
                this.form.meteringNumbers = this.gettime;
            })
        },
        goBack() {
            uni.navigateBack();
        },
        submitForm() {
            // 验证必填字段
            if (!this.form.projectNum) {
                uni.showToast({
                    title: '请输入工程量',
                    icon: 'none'
                });
                return;
            }

            // 处理addNum和upperlimitNum相加
            let addNum = parseFloat(this.form.addNum) || 0;
            let projectNum = parseFloat(this.form.projectNum) || 0;
            let totalNum = addNum + projectNum;
			
            // 验证数值是否有效
            if (isNaN(totalNum)) {
                uni.showToast({
                    title: '数值计算错误',
                    icon: 'none'
                });
                return;
            }

            // 验证合同字段（如果需要的话）
            let upperlimitNum = parseFloat(this.form.upperlimitNum)
			console.log(totalNum,upperlimitNum);
			const num = upperlimitNum - addNum
            if (totalNum > upperlimitNum) {
                uni.showToast({
                    title: `该清单核算可计量部分为${num}，您已超量，请重新输入工程量！`,
                    icon: 'none',
					duration:3000
                });
                return;
            }

            // 调用API提交数据
            addMeteringpay(this.form).then(res => {
                if (res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success'
                    });

                    // 返回上一页
                    setTimeout(() => {
                        //返回计量页
                        uni.switchTab({
                            url: `/pages/metering/index`
                        });
                    }, 1500);
                } else {
                    uni.showToast({
                        title: res.msg || '提交失败',
                        icon: 'none'
                    });
                }
            }).catch(error => {
                console.error('提交失败:', error);
                uni.showToast({
                    title: '提交失败',
                    icon: 'none'
                });
            });
        }
    }
}
</script>

<style lang="scss" scoped>
* {
    box-sizing: border-box;
}

.list {
    height: 1460rpx;
    padding: 0 30rpx;
    background-color: #fff;

    .list-item {
        display: flex;
        align-items: center;
        height: 112rpx;
        border-bottom: 1rpx solid #C9CDD4;

        .select {
            display: flex;
            align-items: center;
            padding-left: 28rpx;
        }

        .item-left {
            margin-right: 32rpx;
            width: 160rpx;
        }

        .item-right {
            flex: 1;
        }

        .input {
            border: 0;
        }
    }
}


.form-content {
    height: calc(100vh - 180rpx);
    overflow: scroll;
}

.form-list {
    flex-direction: column;
}

.form-item {
    display: flex;
    flex-direction: row;
    padding: 0 16px;
    border-bottom-width: 0.5px;
    border-bottom-color: #EEEEEE;
    border-bottom-style: solid;
    width: 359px;
    height: 56px;
    align-self: center;
    align-items: center;
}
.textarea{
	height: 100px;
}

.form-label {
    width: 81px;
    height: 24px;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    line-height: 24px;
}

.form-input {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
    height: 56px;
    width: 100%;
    border: none;
    outline: none;
    background: transparent;
}

.input-wrapper {
    flex: 1;
    margin-left: 16px;
    max-width: 450rpx;
    width: 450rpx;

    :deep(.uni-input-input) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}

.placeholder {
    width: 100%;
    color: rgba(29, 33, 41, 0.65);
}

.submit-button {
    padding: 0 30px;
    margin-top: 84px;
    margin-bottom: 30px;
    width: 100%;
}
.blank_box{
	height: 1px;
}

.submit-btn {
    height: 44px;
    border-radius: 22px;
    font-size: 16px;
    color: #4980FF;
    background-color: #F0F5FF;
    border-width: 0;
    justify-content: center;
    align-items: center;
    font-weight: 500;
    width: 100%;
}
</style>